package com.gesture;

import java.util.LinkedList;
import java.util.List;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;

import com.notification.NotificationSetting;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;

public class GestureControlActivity extends Activity {

	private static final String TAG = "GestureControlActivity";
	private ColorDetectionView mView;
	protected LinkedList<Integer> gestures = new LinkedList<Integer>();
	TrackStatus track ;

	private BaseLoaderCallback mOpenCVCallBack = new BaseLoaderCallback(this) {
		@Override
		public void onManagerConnected(int status) {
			switch (status) {
			case LoaderCallbackInterface.SUCCESS: {
				Log.i(TAG, "OpenCV loaded successfully");
				// Create and set View
				mView = new ColorDetectionView(mAppContext, gestures);
				
				setContentView(mView);
				// Check native OpenCV camera
				if (!mView.openCamera()) {
					AlertDialog ad = new AlertDialog.Builder(mAppContext).create();
					ad.setCancelable(false); // This blocks the 'BACK' button
					ad.setMessage("Fatal error: can't open camera!");
					ad.setButton("OK", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							finish();
						}
					});
					ad.show();
				} else {
				}
			}
				break;
			default: {
				super.onManagerConnected(status);
			}
				break;
			}
		}
	};

	public GestureControlActivity() {
		Log.i(TAG, "Instantiated new " + this.getClass());
		NotificationSetting setting = new NotificationSetting();
		setting.load();
		for (int gest : setting.getGesture()) {
			if (gest == 0)
				break;
			gestures.add(gest);
		}
	}

	protected void onDestroy(){
		Log.i(TAG, "onDestroy()");
		super.onDestroy();
		if (null != mView)
			mView.releaseCamera();
	}
	
	@Override
 	protected void onPause() {
		Log.i(TAG, "onPause");
		super.onPause();
		if (null != mView)
			mView.releaseCamera();
		finish();
	}

	@Override
	protected void onResume() {
		Log.i(TAG, "onResume");
		super.onResume();
		if ((null != mView) && !mView.openCamera()) {
			AlertDialog ad = new AlertDialog.Builder(this).create();
			ad.setCancelable(false); // This blocks the 'BACK' button
			ad.setMessage("Fatal error: can't open camera!");
			ad.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					finish();
				}
			});
			ad.show();
		} else {
		}
	}

	/** Called when the activity is first created. */
	
	public void onCreate(Bundle savedInstanceState) {
		Log.i(TAG, "onCreate");
		super.onCreate(savedInstanceState);
		getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
						| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
						| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

		Log.i(TAG, "Trying to load OpenCV library");
		if (!OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_2, this,
				mOpenCVCallBack)) {
			Log.e(TAG, "Cannot connect to OpenCV Manager");
		} else {
			track = new TrackStatus();
			track.execute();
		}

	}

	private class TrackStatus extends AsyncTask<Void, Integer, Void> {
		final int WAIT_Time = 1000, MAX_Time = 100 * WAIT_Time;
		int status = 0;

		@Override
		protected synchronized Void doInBackground(Void... params) {
			Log.d(TAG, "color: Background Process.");
			int time = 0;
			while (mView == null)
				try {
					wait(WAIT_Time);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			while (status == 0 && time < MAX_Time) {
				try {
					wait(WAIT_Time);
					time += WAIT_Time;
					status = mView.getStatus();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			Log.d(TAG, "status: " + status);
			return null;
		}

		protected void onPostExecute(Void result) {
			mView.releaseCamera();
			mView = null;
			Intent returnSetting = new Intent();
			returnSetting.putExtra("status", status);
			setResult(Activity.RESULT_OK, returnSetting);
			Log.d(TAG, "TrackStatus.onPostExecute(): " + status);
			finish();
		}
	}
}